const { GraphQLServer } = require('graphql-yoga')
const { makeExecutableSchema } = require('graphql-tools')
const { importSchema } = require('graphql-import')
// const { prisma } = require('../generated/prisma')
const { binding } = require('./binding')
// const redis = require('redis')

const resolvers = require('./resolvers')
const { directiveResolvers } = require('./directives')
const checkJwt = require('./middleware/checkJwt')
const { getUser } = require('./middleware/getUser')

console.log(process.env.NODE_ENV)

// const isProd = process.env.NODE_ENV === 'production'

/* const client = redis.createClient()

client.on('error', function (err) {
  console.log('Error ' + err)
}) */

const schema = makeExecutableSchema({
  typeDefs: importSchema('src/schema.graphql'),
  resolvers,
  directiveResolvers
})

const server = new GraphQLServer({
  schema,
  context: req => ({
    // redis: client,
    ...req,
    db: binding /* ,
    db: prisma */
  })
})

server.express.post(
  server.options.endpoint,
  checkJwt,
  (err, req, res, next) => {
    console.log(err, req, res)
    if (err && err.name === 'UnauthorizedError') {
      return res.status(401).send(err.message)
    }
    next()
  }
)

server.express.post(server.options.endpoint, (req, res, next) =>
  getUser(req, res, next, binding)
)

server.start(() => console.log('Server is running on http://localhost:4000'))
